package com.ssyc.student.activity;

import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.ssyc.common.adapter.VpCommonAdapter;
import com.ssyc.common.base.BaseActivity;
import com.ssyc.common.bean.BusInfo;
import com.ssyc.common.http.HttpAdress;
import com.ssyc.common.http.HttpUtils;
import com.ssyc.common.manager.AccountUtils;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.utils.UIHelper;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.common.view.ZzHorizontalProgressBar;
import com.ssyc.common.view.vp.SuperViewPager;
import com.ssyc.student.R;
import com.ssyc.student.bean.ErrorQuestionsInfo;
import com.ssyc.student.fragment.StudentErrorConjunctionsFragment;
import com.ssyc.student.fragment.StudentErrorSingleChooseFragment;
import com.ssyc.student.fragment.StudentErrorTranslateFragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 学生端--金牌金概念2--题型选择--语法错题界面
 * Created by Kevin on 2018/5/29
 */

public class StudentErrorQuestionsActivity extends BaseActivity implements View.OnClickListener, ViewPager.OnPageChangeListener {

    //返回按钮
    private ImageView ivBack;

    //底部的ViewPager
    private SuperViewPager vp;

    //底部的显示Vp页数的文本
    private TextView tvPos;

    //填充ViewPager的Fragment集合
    private List<Fragment> mFragments;

    //ViewPager的适配器
    private VpCommonAdapter adapter;

    //记录当前ViewPager滑动的位置
    private int pos = 0;

    //Handler对象
    private Handler handler = new Handler();

    //进度条
    private ZzHorizontalProgressBar pb;

    //获取LessonId的key
    public static final String LESSONID = "lessonid";

    //获取GradeId的key
    public static final String GRADEID = "gradeid";

    //LessonId
    private String lessonId;

    //GradeId
    private String gradeId;

    private ErrorQuestionsInfo errorInfo;

    //移除题目后刷新数据
    public static final String DELREFLASH = "delreflash";

    @Override
    protected boolean isNeedShowTitle() {
        return false;
    }

    @Override
    protected String setTitleText() {
        return null;
    }

    @Override
    protected int getContentLayout() {
        return R.layout.student_activity_error_questions;
    }

    @Override
    protected void init() {

        //初始化View
        initView();

        //获取传递过来的对象
        initIntent();

        //请求服务器
        http();
    }


    /**
     * 初始化控件
     */
    public void initView() {
        ivBack = findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);
        vp = findViewById(R.id.vp);
        tvPos = findViewById(R.id.tv_vp_pos);
        vp.addOnPageChangeListener(this);
        pb = findViewById(R.id.pb);
    }

    /**
     * 获取传递过来的对象
     */
    private void initIntent() {
        lessonId = getIntent().getStringExtra(LESSONID);
//      gradeId = getIntent().getStringExtra(GRADEID);
    }


    /**
     * 请求服务器
     */
    private void http() {

        Map<String, String> map = new HashMap<>();
        map.put("type", "31");
        map.put("acc", AccountUtils.getAccount(this));
        map.put("lessonId", lessonId);
        map.put("role", AccountUtils.getRole(this));
        map.put("apptoken", AccountUtils.getToken(this));
//        map.put("acc", "15608630008");
//        map.put("lessonId", "1");
//        map.put("role","0");
//        map.put("apptoken", "WHBHWJDSAKDAKSDNSAJDAK");
        map.put("platform", "8");

        HttpUtils.post(HttpAdress.ERRORQUESTIONS, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                UiUtils.Toast("网络错误", false);
            }

            @Override
            public void onResponse(String response, int id) {
                showContent();
                ErrorQuestionsInfo info = null;
                try {
                    info = GsonUtil.jsonToBean(response, ErrorQuestionsInfo.class);
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.i("test", "数据解析异常");
                }
                Log.i("test", "错题集：" + response);
                if (null != info) {
                    if ("200".equals(info.getState())) {
                        //返回成功
                        //初始化Fragments
                        initFragments(info);

                        //初始化Vp的操作
                        initVp();

                        errorInfo = info;
                    } else {
                        Log.i("test", info.getState() + "");
                    }
                }
            }
        });
    }


    /**
     * 初始化Fragments的方法,需要在请求服务器后获取到数据后执行
     */
    private void initFragments(ErrorQuestionsInfo info) {
        mFragments = new ArrayList<>();
        //判断错题集非空
        if(info.getData().getError_list()!=null&&info.getData().getError_list().size()!=0){

        for (int i = 0; i < info.getData().getError_list().size(); i++) {
            if ("29".equals(info.getData().getError_list().get(i).getTypeId())) {
                //连词成句
                mFragments.add(StudentErrorConjunctionsFragment.newInstance(
                        GsonUtil.objectToJson(info.getData()), i));
            } else if ("30".equals(info.getData().getError_list().get(i).getTypeId())) {
                //翻译
                mFragments.add(StudentErrorTranslateFragment.newInstance(
                        GsonUtil.objectToJson(info.getData()), i));
            } else if ("31".equals(info.getData().getError_list().get(i).getTypeId())) {
                //单选
                mFragments.add(StudentErrorSingleChooseFragment.newInstance(
                        GsonUtil.objectToJson(info.getData()), i));
            }
        }

        //添加最后一个提交页面的Fragment
//        mFragments.add(StudentGrammarCommitFragment.newInstance(GsonUtil.objectToJson(info), lessonId, gradeId,energy));

        //设置当前展示的Vp的页码
        tvPos.setText("1/" + (mFragments.size()));

        //设置默认进度条的值
        pb.setProgress((int) ((float) (1) / (float) (mFragments.size()) * 100));
        }else{
            UIHelper.showToast(this,"目前没有产生错题");
        }
    }


    /**
     * 设置ViewPager的方法
     */
    private void initVp() {
        adapter = new VpCommonAdapter(getSupportFragmentManager(), mFragments);
        vp.setAdapter(adapter);
        vp.setOffscreenPageLimit(mFragments.size());
    }

    /**
     * ViewPager的滚动监听
     *
     * @param position
     * @param positionOffset
     * @param positionOffsetPixels
     */
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        pos = position;
//        if (position != mFragments.size() - 1) {
//            tvPos.setVisibility(View.VISIBLE);
//            tvPos.setText((position + 1) + "/" + (mFragments.size() - 1));
//        } else {
//            tvPos.setVisibility(View.GONE);
//        }
//        //记录当前滑动位置
//        currPos = position;
//        //复制vp滑动的最大位置值
//        if (position > maxPos) {
//            maxPos = position;
//        }
//        //根据当前位置来设置Vp是否可以向右滑动
//        if (currPos < maxPos) {
//            //如果当前位置小于Vp滑动过的最大位置,则可以右滑,否则不能右滑
//            vp.setScrollble(true);
//        } else {
//            vp.setScrollble(false);
//        }

        //最后一个位置不进行设置
        if (position != mFragments.size()) {
            //设置进度条的文本显示值
            tvPos.setText((position + 1) + "/" + (mFragments.size()));

            //同时需要设置进度条的值
            pb.setProgress((int) ((float) (pos + 1) / (float) (mFragments.size()) * 100));
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    /**
     * 接受事件的方法
     *
     * @param busInfo
     */
    @Override
    public void busEvent(BusInfo busInfo) {
        super.busEvent(busInfo);
        if (null != busInfo && DELREFLASH.equals(busInfo.msg)) {

            if (busInfo.getPos() < mFragments.size()) {
                //移除
                errorInfo.getData().getError_list().remove(busInfo.getPos());

                initFragments(errorInfo);

                if (errorInfo.getData().getError_list().size() == 0) {
                    UIHelper.showToast(this, "已移除所有错题");
                }
                initVp();
                if (busInfo.getPos() != 0) {
                    vp.setCurrentItem(busInfo.getPos() - 1);
                }
            }
        }
    }


    /**
     * 页面控件的点击事件
     *
     * @param view
     */
    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_back) {
            //关闭
            finish();
        }
    }
}
